package com.quanyan.user.mq.Consumer;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.quanyan.common.constants.MqConstants;
import com.quanyan.common.utils.ObjectUtil;
import com.quanyan.mq.enums.MqConsumerStatus;
import com.quanyan.mq.mq.consumer.AbstractMqConsumer;
import com.quanyan.mq.mq.consumer.MqTopic;
import com.quanyan.user.mapper.TbMedalMapper;
import com.quanyan.user.mapper.TbMedalRuleMapper;
import com.quanyan.user.mapper.TbUserMedalRelationHistoryMapper;
import com.quanyan.user.mapper.TbUserMedalRelationMapper;
import com.quanyan.user.model.db.*;
import com.quanyan.user.mq.UserMedalMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * Created by zhang on 16/7/26.
 */
@Component(value = "mqUserMedalConsumer")
public class MqUserMedalConsumer extends AbstractMqConsumer {

    public static final Logger logger = LoggerFactory.getLogger(MqUserMedalConsumer.class);

    @Value("${mq.nameServer.address}")
    private String nameServerAddress;

    @Autowired
    private TbMedalRuleMapper medalRuleMapper;
    @Autowired
    private TbUserMedalRelationMapper userMedalRelationMapper;
    @Autowired
    private TbUserMedalRelationHistoryMapper userMedalRelationHistoryMapper;

    @PostConstruct
    @Override
    public void start() {
        logger.info("个人勋章消费mq启动成功: {}",nameServerAddress);
        super.start();
    }

    @Override
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    protected MqConsumerStatus process(List<MessageExt> messages, ConsumeConcurrentlyContext context) {
        MessageExt messageExt = messages.get(0);
        String msgId = messageExt.getKeys();

        //判断消息是否被消费
        List<TbUserMedalRelationHistory> userMedalRelationHistoryList = this.getUserMedalRelationHistroyList(msgId);
        if (userMedalRelationHistoryList.isEmpty()) {
            byte[] bodyBytes = messageExt.getBody();
            UserMedalMsg userMedalMsg = (UserMedalMsg) ObjectUtil.toObject(bodyBytes);
            Integer uid = userMedalMsg.getUid();
            Integer medalId = userMedalMsg.getMedalId();
            Integer categoryId = userMedalMsg.getCategoryId();
            TbUserMedalRelationHistory userMedalRelationHistory = new TbUserMedalRelationHistory();
            userMedalRelationHistory.setCategoryId(categoryId);
            userMedalRelationHistory.setUid(uid);
            userMedalRelationHistory.setMedalId(medalId);
            userMedalRelationHistory.setMsgId(msgId);
            this.userMedalRelationHistoryMapper.insertSelective(userMedalRelationHistory);

            logger.info("开始消费用户勋章消息：【msgId】:【{}】;【uid】:【{}】;【medalId】:【{}】",msgId,uid,medalId);

            List<TbUserMedalRelation> userMedalRelationList = this.getUserMedalRelation(medalId,uid);
            if (!userMedalRelationList.isEmpty()) {
                TbUserMedalRelation userMedalRelation = userMedalRelationList.get(0);

                Integer ownValue = userMedalRelation.getOwnValue() + 1;

                List<TbMedalRule> medalRuleList = this.getMedalRuleList(medalId);
                for (TbMedalRule tbMedalRule : medalRuleList) {
                    if(tbMedalRule.getMedalStartLevel().intValue() ==3){
                        if (!userMedalRelation.getGoalValue().equals(tbMedalRule.getStandardValue())) {
                            userMedalRelation.setGoalValue(tbMedalRule.getStandardValue());
                        }
                        if (ownValue.intValue() >= tbMedalRule.getStandardValue().intValue()) {
                            ownValue = tbMedalRule.getStandardValue();
                        }
                    }
                    if(ownValue.intValue() >= tbMedalRule.getStandardValue().intValue()){
                        userMedalRelation.setMedalStartLevel(tbMedalRule.getMedalStartLevel());
                        break;
                    }
                }
                userMedalRelation.setOwnValue(ownValue);
                int n = this.updateUserMedalRelation(medalId,uid,userMedalRelation);
                if (n>0) {
                    userMedalRelationHistory.setStatus(1);
                    this.updateUserMedalRelationHistory(userMedalRelationHistory);
                }else{
                    userMedalRelationHistory.setStatus(2);
                    this.updateUserMedalRelationHistory(userMedalRelationHistory);
                }

            }else{
                logger.warn("该用户【{}】 该勋章【{}】不存在",uid,medalId);
                userMedalRelationHistory.setStatus(3);
                this.updateUserMedalRelationHistory(userMedalRelationHistory);
            }
        }



        return null;
    }

    @Override
    protected String getConsumerGroup() {
        return MqConstants.UserMedalProducer.USER_MEDAL_GROUP;
    }

    @Override
    protected String getNameServerAddress() {
        return this.nameServerAddress;
    }

    @Override
    protected String getInstanceName() {
        return MqConstants.UserMedalProducer.USER_MEDAL_INSTANCE;
    }

    @Override
    protected MqTopic[] getMqTopics() {
        MqTopic[] mqTopics = new MqTopic[1];
        mqTopics[0] = new MqTopic(MqConstants.UserMedalConsumer.USERE_MEDAL_TOPIC,MqConstants.UserMedalConsumer.USER_MEDAL_TAGS);
        return mqTopics;
    }

    /**
     * 获取用户勋章信息
     * @param medalId
     * @param uid
     * @return
     */
    private List<TbUserMedalRelation> getUserMedalRelation(Integer medalId,Integer uid){
        TbUserMedalRelationExample example = new TbUserMedalRelationExample();
        example.createCriteria().andUidEqualTo(uid).andMedalIdEqualTo(medalId);
        List<TbUserMedalRelation> userMedalRelationList = this.userMedalRelationMapper.selectByExample(example);
        return userMedalRelationList;
    }

    /**
     * 更新用户勋章
     * @param medalId
     * @param uid
     * @param userMedalRelation
     * @return
     */
    private int updateUserMedalRelation(Integer medalId,Integer uid,TbUserMedalRelation userMedalRelation){

        TbUserMedalRelationExample example = new TbUserMedalRelationExample();
        example.createCriteria().andMedalIdEqualTo(medalId).andUidEqualTo(uid);

        int n = this.userMedalRelationMapper.updateByExampleSelective(userMedalRelation,example);
        return n;
    }

    /**
     * 获取用户勋章规则
     * @param medalId
     * @return
     */
    private List<TbMedalRule> getMedalRuleList(Integer medalId){
        TbMedalRuleExample example = new TbMedalRuleExample();
        example.setOrderByClause("medal_start_level desc");
        example.createCriteria().andMedalIdEqualTo(medalId);
        List<TbMedalRule> medalRuleList = this.medalRuleMapper.selectByExample(example);
        return medalRuleList;
    }

    /**
     * 获取用户勋章消费历史记录
     * @param msgId
     * @return
     */
    private List<TbUserMedalRelationHistory> getUserMedalRelationHistroyList(String msgId){
        TbUserMedalRelationHistoryExample example = new TbUserMedalRelationHistoryExample();
        example.createCriteria().andMsgIdEqualTo(msgId);
        List<TbUserMedalRelationHistory> userMedalRelationHistoryList = this.userMedalRelationHistoryMapper.selectByExample(example);
        return userMedalRelationHistoryList;
    }

    /**
     * 通过主键更新用户勋章消费信息
     * @param userMedalRelationHistory
     * @return
     */
    private int updateUserMedalRelationHistory(TbUserMedalRelationHistory userMedalRelationHistory){
        int n = this.userMedalRelationHistoryMapper.updateByPrimaryKeySelective(userMedalRelationHistory);
        return n;
    }
}
